package com.qiudaozhang.jblog.backend.interceptors;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 邱道长
 * 时间： 2018/12/23 11:39
 */
@Component
public class LoginSessionInterceptor implements HandlerInterceptor {

    // 前置处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if((requestURI.startsWith("/admin/") || requestURI.equals("/"))
                && !requestURI.equals("/to/login")
                && !requestURI.equals("/login")){
            // 检查是否有用户存在
            Object user = request.getSession().getAttribute("user");
            if(user == null){
                response.sendRedirect("/to/login");
                return false;
            }
        }
        return true;
    }

    // 提交处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    // 后置处理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
